/*
 * Filename: g:\espidf_workspace\idf_S3_T-Watch\main\app\music.cc
 * Path: g:\espidf_workspace\idf_S3_T-Watch\main\app
 * Created Date: Tuesday, July 1st 2025, 10:25:08 am
 * Author: sss
 *
 * Copyright (c) 2025 Your Company
 */
#include "music.h"
#include "my_ui.h"
#include "esp_log.h"
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "wifi.h"
#include "adf_service.h"

extern "C"
{
#include "http_rest_json_client.h"
}

static const char *TAG = "Music";

#if LV_USE_MSGBOX
static void event_cb(lv_event_t *e)
{
    lv_obj_t *obj = lv_event_get_current_target(e);
    LV_LOG_USER("Button %s clicked", lv_msgbox_get_active_btn_text(obj));
}

void lv_example_msgbox(const char *title, const char *text)
{
    static const char *btns[] = {"Apply", "Close", ""};

    lv_obj_t *mbox1 = lv_msgbox_create(NULL, title, text, btns, true);
    lv_obj_add_event_cb(mbox1, event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    lv_obj_center(mbox1);
}
#endif

// int music_list_index = 0;
// const char *musiclist[3] = {
//     "http://192.168.1.5:8090/test1.mp3",
//     "http://192.168.1.5:8090/test2.mp3",
//     "http://192.168.1.5:8090/output.pcm",
//     };

static void music_callback(void *s, lv_msg_t *msg)
{
    Wifi &wifi = Wifi::get_instance();
    // AUDIO_PLAYER &audio_player = AUDIO_PLAYER::get_instance();
    ADF_SERVICE &adf_service = ADF_SERVICE::get_instance();
    Music &music = Music::get_instance();

    vTaskDelay(pdMS_TO_TICKS(100));

    if (wifi.is_connected() == false)
    {
        lv_example_msgbox("WIFI ERROR", "Please connect to WIFI");
        return;
    }

    if (msg->id == MSG_MUSIC_NEXT)
    {
        music.play_next();
    }
    else if (msg->id == MSG_MUSIC_PREV)
    {
        music.play_prev();
    }
    else if (msg->id == MSG_MUSIC_PLAY)
    {
        music.play();
    }
    else if (msg->id == MSG_MUSIC_PAUSE)
    {
        music.pause();
    }
}

static void ui_event_controller()
{
    lv_msg_subscribe(MSG_MUSIC_PLAY, music_callback, NULL);
    lv_msg_subscribe(MSG_MUSIC_PAUSE, music_callback, NULL);
    lv_msg_subscribe(MSG_MUSIC_PREV, music_callback, NULL);
    lv_msg_subscribe(MSG_MUSIC_NEXT, music_callback, NULL);
}

void Music::play()
{
    ESP_LOGI(TAG, "play");
    playing = true;

    if (ui_PlayBtn && ui_PauseBtn)
    {
        lv_obj_add_flag(ui_PlayBtn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_PauseBtn, LV_OBJ_FLAG_HIDDEN);
    }

    if (ui_Label12)
    {
        std::string title_string = "";
        title_string.append(songs[song_index].artist).append(" - ").append(songs[song_index].name);
        const char *title = title_string.c_str();
        lv_label_set_text(ui_Label12, title);
    }
    // if(ui_Image1){
    //     lv_img_set_src(ui_Image1, songs[song_index].album.c_str());
    // }

    MusicInfo info = songs[song_index];
    const char *url = info.path.c_str();
    vTaskDelay(pdMS_TO_TICKS(100));

    ADF_SERVICE &adf_service = ADF_SERVICE::get_instance();
    adf_service.play_url(url);
}

void Music::pause()
{
    ESP_LOGI(TAG, "pause");
    playing = false;
    if (ui_PlayBtn && ui_PauseBtn)
    {
        lv_obj_add_flag(ui_PauseBtn, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_PlayBtn, LV_OBJ_FLAG_HIDDEN);
    }
    vTaskDelay(pdMS_TO_TICKS(100));
    ADF_SERVICE &adf_service = ADF_SERVICE::get_instance();
    adf_service.pause_play();
}

void Music::stop()
{
    pause();
    track_duration = 0;
    vTaskDelay(pdMS_TO_TICKS(300));
}

void Music::play_next()
{
    // TODO: implement
    ESP_LOGI(TAG, "play_next");
    stop();
    song_index++;
    if (song_index >= songs.size())
    {
        song_index = 0;
    }
    play();
}

void Music::play_prev()
{
    // TODO: implement
    ESP_LOGI(TAG, "play_prev");
    stop();
    song_index--;
    if (song_index < 0)
    {
        song_index = songs.size() - 1;
    }
    play();
}

void Music::get_song_list(const char *http_url)
{
    char *http_url_buffer = (char *)malloc(strlen(http_url) + 1);
    strcpy(http_url_buffer, http_url);
    http_rest_recv_json_t response_buffer = {0};

    // do the request
    ESP_ERROR_CHECK(http_rest_client_get_json(http_url_buffer, &response_buffer));

    if (response_buffer.status_code != 200)
    {
        ESP_LOGE(TAG, "an http error occured: %d", response_buffer.status_code);
    }
    else
    {
        char *jsonString = cJSON_Print(response_buffer.json);
        ESP_LOGI(TAG, "Response: %s", jsonString);

        // parse the json response
        cJSON *root = cJSON_Parse(jsonString);
        if (root == NULL)
        {
            /* code */
            ESP_LOGE(TAG, "Error parsing JSON");
            return;
        }

        int songs_count = cJSON_GetArraySize(root);
        for (int i = 0; i < songs_count; i++)
        {
            cJSON *song = cJSON_GetArrayItem(root, i);
            if (song == NULL)
            {
                continue;
            }
            MusicInfo info;
            info.name = cJSON_GetObjectItem(song, "name")->valuestring;
            info.path = cJSON_GetObjectItem(song, "path")->valuestring;
            info.artist = cJSON_GetObjectItem(song, "artist")->valuestring;
            info.album = cJSON_GetObjectItem(song, "album")->valuestring;
            info.duration = cJSON_GetObjectItem(song, "duration")->valueint;
            add_song(info);
        }

        free(jsonString);
    }
    free(http_url_buffer);
    http_rest_client_cleanup_json(&response_buffer);
}

void Music::add_song(MusicInfo song)
{
    ESP_LOGI(TAG, "Adding song: %s", song.name.c_str());
    songs.push_back(song);
}

Music::Music()
{
    ui_event_controller();
    // get_song_list("http://fxdp.panogk.cn/testsound/sound.php");
}

Music::~Music()
{
}